var Screenshot = {
	Meta: {
		// Metadata about shot and uploader
		user_name: $('.shot-byline-user a.url').text(),
		user_twitter: function() {
			if($('meta[name="twitter:creator"]').length > 0) {
				return $('meta[name="twitter:creator"]').attr("content");
			} else {
				return Screenshot.Meta.user_name;
			}
		},
		team_name: $('.shot-byline-team a.url').text(),
		team_twitter: $('.shot-byline-team a.url').text(),
		full_url: window.location.href.split('?')[0],
		short_url: $('#meta-short-url').text(),
		title: $('#screenshot-title').text(),
		img: $('meta[property="og:image"]').attr("content")
	},
	Like: {
		// Like or unlike a screenshot or comment
		Shot: {
			toggle: function() {
				if ($('.fav a.fav-toggle.processing').length == 0) {
					var $link = $(".fav a.fav-toggle");
					var url = $link.attr('href');
					var data = $link.hasClass('current-user-likes') ? {_method: 'delete'} : {}

					$.ajax({
						type: 'POST',
						url: url,
						data: data,
						beforeSend: function() {
							$('.fav-toggle').addClass('processing');
							$link.text('Wait...');
						},
						success: function(responseHtml) {
							$('#like-section').replaceWith(responseHtml);
						}
					});
				}

				return false;
			}
		},
		Comment: {
				toggle: function() {
					var link = $(this);
					var data = link.hasClass('liked-by-current-user') ? {_method: 'delete'} : null;
					$.ajax({
						type: 'POST',
						url: this.href,
						data: data,
						success: function(responseHtml) {
							var $response = $(responseHtml);
							var $previousComment = link.closest('.comment');

							if ($previousComment.find('.reply').length) {
								makeCommentReplyable($response);
							}

							$previousComment.replaceWith($response);
						}
					});

					return false;
			}
		}
	},
	Flag: {
		// Flag a screenshot as inappropriate or Appropriate
		flag: function(){
			var link = $(this);
			var screenshotId = link.modelId();
			if(!confirm("You are about to report this shot as abuse of Dribbble. Are you sure you wish to continue?"))
				return false;

			$.ajax({
				type: 'POST',
				url: this.href,
				data: {
					screenshot_id: screenshotId
				},
				success: function(responseHtml) {
					$('#flag-section').html(responseHtml);
				}
			});

			return false;
		},
		unflag: function() {
			var link = $(this);
			var screenshotId = link.modelId();
			$.ajax({
				type: 'POST',
				url: this.href,
				data: {
					_method: 'delete',
					screenshot_id: screenshotId
				},
				success: function(responseHtml) {
					$('#flag-section').html(responseHtml);
				}
			});

			return false;
		}
	},
	Keyboard: {
		// Key Constants
		b_key: 66,
		f_key: 70,
		l_key: 76,
		left_arrow: 37,
		right_arrow: 39,

		handle: function(e) {
			if(Screenshot.Keyboard.is_valid_event(e)){
				var code = e.which;

				switch(code){
					case Screenshot.Keyboard.f_key: // l and f do the same thing
					case Screenshot.Keyboard.l_key:
						if($('.logged-in').length > 0)
							Screenshot.Like.Shot.toggle();
						break;
					case Screenshot.Keyboard.b_key:
						$(".screenshot-meta .bucket a.meta-bucket").click();
						break;
					case Screenshot.Keyboard.left_arrow:
						Screenshot.Page.prev();
						break;
					case Screenshot.Keyboard.right_arrow:
						Screenshot.Page.next();
						break;
				}
			}
		},
		is_valid_event: function(e) {
			// Check if the target is the main page. This prevents an
			// event from firing when a person is typing a comment,
			// or in the search bar.
			if (e.target.localName == 'body' || e.target.localName == 'html')
				if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey)
				return true;

			return false;
		}
	},
	Page: {
		next: function() {
			var href = $('.secondary .prevnext:first .next a').attr('href');
			if (href && href != newLocation) {
				document.location = href;
				newLocation = href;
			}
		},
		prev: function() {
			var href = $('.secondary .prevnext:first .prev a').attr('href');
			if (href && href != newLocation) {
				document.location = href;
				newLocation = href;
			}
		}
	}
};

// Events

// Flag screenshot as inappropriate
$(".admin a.flag").live('click', Screenshot.Flag.flag);
$(".admin a.unflag").live('click', Screenshot.Flag.unflag);

// Like or unlike a screenshot
$(".fav a.fav-toggle").live('click', Screenshot.Like.Shot.toggle);

// Keyboard shortcut for faving screenshot
$(document).keyup(Screenshot.Keyboard.handle);

// Toggle share links wrapper
$(".meta-share").live('click', function() {
	$("#share-links").slideToggle(200);
	return false;
});

// Like or unlike a comment
$(".comment a.likes").live('click', Screenshot.Like.Comment.toggle);

// Highlight short URL when clicked
$('#share-form-url').click(function(){
		this.select();
	});

// Only show tipsy on wide-ish screens
if (window.matchMedia("screen and (min-width: " + DEVICE_WIDTH_BREAKPOINT + ")").matches) {
	$('a.twotimes').tipsy({fade: true, gravity: 's'});
}

$('a.twotimes').click(function() {
	if (window.matchMedia("screen and (max-width: " + DEVICE_WIDTH_BREAKPOINT + ")").matches) {
		return false;
	}

	var full_class = 'full-800';
	var hidpi = window.matchMedia(HIDPI_BREAKPOINT).matches;
	var $shotDiv = $('.the-shot .single-img');

	if ($('#main').hasClass(full_class)) {
		$('#main').removeClass(full_class);
		$('.secondary').removeClass('hide');

		// Restore @1x image on normal dpi display
		if (!hidpi) {
			var url_1x = $shotDiv.find('[data-picture] div:not([data-media])').attr('data-src');
			// If no picture fill, same image is used, so nothing to do (e.g. animated gifs).
			if (url_1x) $shotDiv.find('img').attr('src', url_1x);
		}
	}
	else {
		$('#main').addClass(full_class);
		$('.secondary').addClass('hide');

		// Show @2x image on normal dpi display
		if (!hidpi) {
			var url_2x = $shotDiv.find('[data-media]').attr('data-src');
			// If no picture fill, same image is used, so nothing to do (e.g. animated gifs).
			if (url_2x) $shotDiv.find('img').attr('src', url_2x);
		}
	}
	return false;
});

var newLocation;

$("#main .the-shot").swipe({
	fingers: 1,
	threshold: 200,
	swipeLeft: Screenshot.Page.next,
	swipeRight: Screenshot.Page.prev
});

$('#share-form-url').click(function(){
		this.select();
	});

	var shorterTotal = function(num) {
		if (num >= 1e6) {
			num = (num / 1e6).toFixed(2) + "M";
		} else if (num >= 1e3) {
			num = (num / 1e3).toFixed(1) + "k";
		}
		return num;
	};

	/* Load share counts from Facebook, Twitter, and Pinterest */

	$.getJSON('https://graph.facebook.com/fql?q=SELECT like_count FROM link_stat WHERE url=' + encodeURIComponent('"' + Screenshot.Meta.full_url + '"') + '	&callback=?', function(data) {
		if (data.data[0]) {
			$('#share-button-fb .shot-social-count').html(shorterTotal(data.data[0].like_count));
		}
	});

	$.getJSON('http://cdn.api.twitter.com/1/urls/count.json?url=' + encodeURIComponent(Screenshot.Meta.full_url) + '&callback=?', function(data) {
		if (data.count) {
			$('#share-button-twitter .shot-social-count').html(shorterTotal(data.count));
		}
	});

	$.getJSON('http://api.pinterest.com/v1/urls/count.json?url=' + encodeURIComponent(Screenshot.Meta.full_url) + '&callback=?', function(data) {
		if (data.count) {
			$('#share-button-pin .shot-social-count').html(shorterTotal(data.count));
		}
	});


	/* Launch sharing windows on click */

	$('#share-button-fb').on('click', function() {
		window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(Screenshot.Meta.full_url), "", "height=350,width=600");
	});

	$('#share-button-pin').on('click', function() {
		var team    = Screenshot.Meta.team_name;
		var message = Screenshot.Meta.title + ' by ' + Screenshot.Meta.user_name;

		if (team) {
			message += ' for ' + team;
		}

		window.open('//pinterest.com/pin/create/button/?url=' + encodeURIComponent(Screenshot.Meta.full_url) + '&media=' + encodeURIComponent(Screenshot.Meta.img) + '&description=' + encodeURIComponent(message), '', 'height=260,width=600');
	});

	$('#share-button-twitter').on('click', function() {
		var team    = Screenshot.Meta.team_twitter;
		var message = Screenshot.Meta.title + ' by ' + Screenshot.Meta.user_twitter()

		if (team) {
			message += ' for ' + team;
		}

		message += ' on @dribbble';

		window.open('https://twitter.com/intent/tweet?url=' + encodeURIComponent(Screenshot.Meta.full_url) + '&text=' + encodeURIComponent(message), '', 'status=0,toolbar=0,height=250,width=600');
	});
